package com.tiantianyuegou.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.widget.ListView;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.R;
import com.tiantianyuegou.adapter.EvaluateAdapter;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.model.EvaluateModel;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.NetworkUtils;
import com.tiantianyuegou.util.TimeUtils;
import com.tiantianyuegou.util.Tools;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * 更多评价
 * Created by huyang on 2016/1/11 0011.
 */
public class EvaluateActivity extends BaseActivity implements View.OnClickListener {

    private PullToRefreshListView refresh;
    private List<EvaluateModel> datas;
    private EvaluateAdapter mAdapter;
    private LoadingDialog loadingDialog;
    private String TAG = "EvaluateActivity";
    private int mPage = 0;
    private boolean isRefresh = true;
    private boolean isLoadMore = false;

    @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_evaluate);
        setTitle("更多评价");
        Tools.changeSystemBar(this);
        initViews();
        loadEvaluate();
    }

    @Override
    public void findViewByIds() {
        refresh = (PullToRefreshListView) findViewById(R.id.list_evaluate);
        //下拉刷新
        ILoadingLayout pullDownRefresh = refresh.getLoadingLayoutProxy(true, false);
        pullDownRefresh.setPullLabel("下拉刷新");//下拉提示
        pullDownRefresh.setRefreshingLabel("正在刷新...");//刷新提示
        pullDownRefresh.setReleaseLabel("松开刷新");//下拉一定距离显示的提示
        //上拉加载
        ILoadingLayout pullUpRefresh = refresh.getLoadingLayoutProxy(false, true);
        pullUpRefresh.setPullLabel("上拉加载");
        pullUpRefresh.setRefreshingLabel("正在刷新...");
        pullUpRefresh.setReleaseLabel("松开加载更多");

    }

    @Override
    public void initListener() {
        loadingDialog = new LoadingDialog(this);
        datas = new ArrayList<>();
        mAdapter = new EvaluateAdapter(this);
        refresh.setAdapter(mAdapter);
        refresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                //下拉刷新
                mPage = 0;
                loadEvaluate();
                isRefresh = true;
                isLoadMore = false;
                String label = DateUtils.formatDateTime(
                        getApplicationContext(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);
                refresh.getLoadingLayoutProxy().setLastUpdatedLabel(label);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                //上拉加载
                loadEvaluate();
                isRefresh = false;
                isLoadMore = true;
                String label = DateUtils.formatDateTime(
                        getApplicationContext(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);
                refresh.getLoadingLayoutProxy().setLastUpdatedLabel(label);
            }
        });

    }

    @Override
    public void initData() {

    }

    public void loadEvaluate() {
        if (!NetworkUtils.isNetworkAvailable(this)) {
            showMsg("请检查网络");
        }
        //String productId = SPHelper.getTPId();
        Intent intent = getIntent();
        String productId = intent.getStringExtra("evaluate");

        loadingDialog.showDialog();
        loadingDialog.setMsg("正在加载");
        RequestParams params = new RequestParams();
        params.addBodyParameter("productId", productId);
        params.addBodyParameter("page", (++mPage) + "");
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.COMMENT_LIST, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                loadingDialog.dismiss();
                refresh.onRefreshComplete();
                Log.e(TAG, "onSuccess response.result" +
                        response.result);

                if (TextUtils.isEmpty(response.result)) {
                    showMsg("获取评论列表失败");
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            JSONArray list = jsonObject.getJSONArray("list");
                            if (isRefresh) {
                                datas.clear();
                                isRefresh = false;
                            } else if (isLoadMore) {
                                isLoadMore = false;
                            }
                            for (int i = 0; i < list.length(); i++) {
                                EvaluateModel model = new EvaluateModel();
                                JSONObject temp = list.getJSONObject(i);
                                String tmName = temp.getString("tmName");
                                String tcContent = temp.getString("tcContent");
                                String tcAddtiem = temp.getString("tcAddtiem");
                                String tcRateGtade = temp.getString("tcRateGtade");
                                String tmAvatar = temp.getString("tmAvatar");
                                Log.e(TAG, "--------tmAvatar=" + tmAvatar);
                                Log.e(TAG, "--------tmName=" + tmName);
                                String tcSpecJson = temp.getString("tcSpecJson");
                                StringBuffer desp = new StringBuffer();
                                if (tcSpecJson.contains("[")) {
                                    JSONArray jsonArray = new JSONArray(tcSpecJson);
                                    for (int j = 0; j < jsonArray.length(); j++) {
//                                        Log.e(TAG, "jsonArray" + jsonArray.length());
                                        JSONObject object = jsonArray.getJSONObject(j);
                                        String tsName = object.getString("tsName");
                                        String value = object.getString("value");
                                        desp.append(tsName).append(":")
                                                .append(value).append("  ");
                                    }
//                                    Log.e("TAG", "product desp array:" + specModel.size());
                                }
                                model.setTmName(tmName);
                                if (tmAvatar != null && !"".equals(tmAvatar)) {
                                    model.setTmAvatar(tmAvatar);
                                } else {
                                    model.setTmAvatar("");
                                }
                                model.setTcRateGtade(tcRateGtade);
                                model.setTcContent(tcContent);
                                model.setTcAddtime(TimeUtils.convertTimeYMD(Long.valueOf(tcAddtiem)));
                                model.setSpecAll(desp.toString());
                                Log.e(TAG, desp.toString());
                                datas.add(model);
                            }
//                            TODO 需换成真是操作数据字段名称
//                            mAdapter.setData(datas);
                            Log.e(TAG, "------------size:" + datas.size());
                            mAdapter.notifyDataSetChanged();
                        } else {
                            if (isLoadMore && datas.size() > 0) {
                                isLoadMore = false;
                                mPage--;
                                showMsg("没有更多评论了");
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        showMsg("评论列表加载失败");
                        if (isRefresh) {
                            isRefresh = false;
                        } else if (isLoadMore) {
                            isLoadMore = false;
                            mPage--;
                        }
                    }
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                loadingDialog.dismiss();
                refresh.onRefreshComplete();
                showMsg("当前网络不可用，请检查网络设置");
                if (isRefresh) {
                    isRefresh = false;
                } else if (isLoadMore) {
                    isLoadMore = false;
                    mPage--;
                }
            }
        });
    }

    @Override
    public void onClick(View view) {

    }
}
